package com.yb.bussiness.goods;

import java.util.List;

import com.yb.base.dao.BaseDao;
import com.yb.base.dao.IBaseDao;
import com.yb.domain.goods.TgMarket;
import com.yb.util.framework.PageUtil;

public class MarketServiceImpl implements MarketService {

	private IBaseDao<TgMarket, Long> dao;

	public MarketServiceImpl() {
		dao = new BaseDao<TgMarket, Long>(TgMarket.class);
	}

	public void deleteMarket(TgMarket market) {
		dao.delete(market);
	}

	public List<TgMarket> findAll(int page, int limit, Long cid) {
		String sql = "select * from t_g_market ";
		if(0l != cid)
			sql += " where instr(CONCAT(',',categoryId,','),',"+cid+",')<>0";
		sql += " order by marketOrder";
		if (-1 != page) {
			sql += " limit ?,? ";
			return dao
					.findList(sql, new Object[] { (page - 1) * limit, limit });
		} else {
			return dao.findList(sql);
		}
	}

	public List<TgMarket> findAll() {
		String sql = "select * from t_g_market order by marketOrder ";
		return dao.findList(sql);
	}

	public TgMarket findById(Long id) {
		return dao.read(id);
	}

	public void save(TgMarket market) {
		dao.saveOrUpdate(market);
	}

	public List<TgMarket> findAllByCategoryId(Long categoryId) {
		StringBuffer sb = new StringBuffer();
		sb
				.append("SELECT * FROM t_g_market tgm WHERE EXISTS (SELECT 1 FROM t_market_brand tmb WHERE tmb.marketId = tgm.id AND ");
		sb
				.append(" EXISTS (SELECT 1 FROM t_pinggou tgb WHERE tgb.brandId = tmb.brandId AND ");
		sb
				.append("tgb.categoryId = ?))");
		return dao.findList(sb.toString(), new Object[] { categoryId });
	}

	public List<TgMarket> findAllByCid(Long cid) {
		String sql = "select * from t_g_market where categoryId is null or instr(CONCAT(',',categoryId,','),',"+cid+",') <> 0";
		return dao.findList(sql);
	}

	public PageUtil findAllByBid(Long bid, int page, int limit) {
		String sql = "select t.* ";
		String countSql = "select count(*) ";
		String tempSql = "from t_g_market t WHERE EXISTS (SELECT 1 FROM t_market_brand tmb WHERE tmb.marketId = t.id and tmb.brandId = ? )";
		String limitSql = " limit ?,?";
		List<TgMarket> list = dao.findList(sql + tempSql + limitSql,
				new Object[] { bid, (page - 1) * limit, limit });
		PageUtil pu = new PageUtil();
		pu.setList(list);
		pu.setPageNo(page);
		pu.setPageSize(limit);
		List<Object[]> countList = dao.findObjectArryList(countSql+tempSql,
				new Object[] { bid });
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			pu.setTotalRecords(new Integer(countAry[0].toString()));
		} else {
			pu.setTotalRecords(0);
		}
		return pu;
	}

}
